package br.edu.ufcg.greengrid.report;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

import br.edu.ufcg.greengrid.event.Event;
import br.edu.ufcg.greengrid.model.Simulator;
import br.edu.ufcg.greengrid.util.ClosableLinkedListImpl;
import br.edu.ufcg.greengrid.util.ClosableList;

import com.mallardsoft.tuple.Tuple;

public abstract class AbstractReporter<E extends Tuple<? extends Comparable<?>, ? extends Comparable<?>>> implements
		Reporter {

	private ClosableList<E> entries;

	private long randomValue;

	public AbstractReporter(long randomValue, ClosableList<E> entries) {
		this.randomValue = randomValue;
		this.entries = entries;
	}
	
	public AbstractReporter(long randomValue) {
		this(randomValue, new ClosableLinkedListImpl<E>());
	}

	protected void add(E e) {
		this.entries.add(e);
	}

	@Override
	public void generateOutput() throws IOException {
		BufferedWriter bw = null;

		try {
			bw = new BufferedWriter(new FileWriter(new File(getOutputName())));

			for (Iterator<E> iter = this.entries.iterator(); iter.hasNext();) {
				bw.write(iter.next().toString("", Event.SEPARATOR, ""));
				bw.newLine();
			}
			
		} finally {
			if (bw != null) {
				bw.close();
			}
		}
	}

	protected static String getOutputName(String reportName, long randomValue) {
		return reportName + "-" + randomValue + ".out";
	}
	
	protected String getOutputName() {
		return getReportName() + "-" + this.randomValue + ".out";
	}

	protected abstract String getReportName();

	public void close(Simulator s){
		
		this.entries.close();
	}
	
	public void cleanUp(Simulator s) {
		
	}

	public void handleNewTimestamp(Simulator s) {

	}
}
